package UDP.EchoServer;

import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 服务器 UdpEchoServer
 */
public class UdpEchoServer {

    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);// 让服务器和这个端口号关联起来
    }

    // 启动服务器
    public void start() throws IOException {
        System.out.println("启动服务器");
        // 直接接受数据
        while (true){
            // 读取请求
            DatagramPacket dataRequest = new DatagramPacket(new byte[1024],1024);
            socket.receive(dataRequest);// 填充数据报
            String request = new String(dataRequest.getData(),0,dataRequest.getLength(),"UTF-8");

            String response = process(request);

            // 指定数据报发给谁,指定地址和端口
            DatagramPacket dataRespond = new DatagramPacket(
                    response.getBytes(),
                    response.getBytes().length,
                    dataRequest.getSocketAddress() //得到发送请求方的地址,按这个地址返回
            );
            socket.send(dataRespond);
        }
    }
    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}

















